#include "box.h"

box::box()
	: QGraphicsRectItem()
{
		setBrush(Qt::white);
		setFlag(QGraphicsItem::ItemIsMovable, true);
		setFlag(QGraphicsItem::ItemIsSelectable, true);
		setFlag(QGraphicsItem::ItemSendsGeometryChanges, true);
		child = NULL;
		nameField = NULL;
		numberField = NULL;
		costField = NULL;
		pNodeField = NULL;
}
box::box(QPointF pos, qreal width, qreal height,int _id,int num, QGraphicsScene *scene)
	: QGraphicsRectItem(0,scene)
{
	setPos(pos);
	setRect(0,0,width,height);
	setBrush(Qt::white);
	setFlag(QGraphicsItem::ItemIsMovable, true);
	setFlag(QGraphicsItem::ItemIsSelectable, true);
	setFlag(QGraphicsItem::ItemSendsGeometryChanges, true);
	child = NULL;
	id = _id;
	number = num;
	cost = 0;	

	name = QString("Block %1").arg(id);	//Текст блока "по умолчанию"

	nameField = new diagramTextItem(QPointF(20,20), name, this);
	numberField = new diagramTextItem(QPointF(105, 60),QString("%1").arg(number), this);
	costField = new diagramTextItem(QPointF(10, 60), QString("%1").arg(cost), this);
	pNodeField = new diagramTextItem(QPointF(100, 87), QString(""), this);
	pNodeField->setFlag(QGraphicsItem::ItemIsSelectable, false);
	correctNodeName();
}   
box::box(const box& other)
{
	*this = other;
	nameField = new diagramTextItem(QPointF(20,20), this->name, this);
	numberField = new diagramTextItem(QPointF(110, 60),QString("%1").arg(this->number), this);
	costField = new diagramTextItem(QPointF(10, 60), QString("%1").arg(this->cost), this);
	pNodeField = new diagramTextItem(QPointF(100, 87), QString(""), this);
	pNodeField->setFlag(QGraphicsItem::ItemIsSelectable, false);
	correctNodeName();
}                       

box::~box()
{
	if (child != NULL )child->killChildren();
	delete child;
	delete nameField;
	delete numberField;
	delete costField;
	delete pNodeField;
}

box& box::operator=(const box& other)
{
	id			= other.id;			//Идентификатор блока
	name		= other.name;		//Название блока
	number		= other.number;		//Номер блока на диаграмме
	cost		= other.cost;		//Стоимость блока
	cost_unit	= other.cost_unit;	//Единица измерения стоимости блока
	links		= other.links;		//Cвязи, инцидентные блоку
	child		= other.child;		//Диаграмма, являющаяся декомпозицией блока
	setRect(other.rect());
	setFlags(other.flags());
	return *this;
}

link::ArrowType box::area(QPointF point)
{
	point -= pos();				//Переход в систему координат блока
	float k = rect().height()/rect().width();//Коэфициент k уравнения прямой y=k*x+b
	float d1 = k*point.x();					//Высота диагонали в этой точке
	float d2 = -k*point.x() + rect().height();//Высота обратной диагонали в этой точке

	if ((point.y() <= d1)&&(point.y() <= d2)) return link::Control;	//Управление
	if ((point.y() > d1)&&(point.y() <= d2)) return link::Input;	//Вход
	if ((point.y() <= d1)&&(point.y() > d2)){ //return link::Output;	//Выход
		if(point.y() <= rect().center().y()) return link::Control;
		else return link::Resource;
	}
	if ((point.y() > d1)&&(point.y() > d2)) return link::Resource;	//Механизм
	return link::Input;
}
void box::TextChanged(void)
{
	name = nameField->mText;
	cost = costField->mText.toInt();
	number = numberField->mText.toInt();
}

void box::correctNodeName(void)
{
	pNodeField->setPos(QPointF(this->rect().right()-pNodeField->boundingRect().right(),87));
}

void box::FieldChanged(void)
{
	nameField->mText = name;
	nameField->setPlainText(name);
	nameField->cutOffText();

	costField->mText = QString("%1").arg(cost);
	costField->setPlainText(QString("%1").arg(cost));

	numberField->mText = QString("%1").arg(number);
	numberField->setPlainText(QString("%1").arg(number));
}

QVariant	box::itemChange ( GraphicsItemChange change, const QVariant & value ){
	if (change == QGraphicsItem::ItemPositionChange){
		QPointF offset = pos() - value.toPointF();
		QList<link::end*> ends;
		bool canMove = true;
		segment *s;
		for (int i = 0; i < links.size(); i++){
			ends = links[i]->to.values(id);
			for (int j = 0; j < ends.size() && canMove; j++){
				canMove = canMove && ends[j]->s->canMoveEndTo(ends[j]->s->p2-offset);
				if (ends[j]->s->prev!=NULL) canMove = canMove && 
					((ends[j]->s->prev->p2-offset)-ends[j]->s->prev->p1).manhattanLength() > STEP*2;
			}
		}
		if (canMove)
		for (int i = 0; i < links.size(); i++){
			if (this == links[i]->from->b){
				/*s = new segment(links[i]->from->s->p1-offset);
				qDebug() << "slen" << links[i]->from->s->len()<< links[i]->from->s->p1-offset; 
				segment::swap(links[i]->from->s,s);*/
				
			}
			else{
				ends = links[i]->to.values(id);
				for (int j = 0; j < ends.size(); j++){
					s = ends[j]->s;
					QPointF oldP2 = s->p2;
					if (s->prev != NULL){ 
						int s_pos = s->prev->next.indexOf(s);
						s = s->prev;
						delete s->next[s_pos];
						s->next.removeAt(s_pos);
					}
					ends[j]->s = s->extendTo(oldP2-offset);	
				}
				
			}
			links[i]->update();
		}
		else return QGraphicsRectItem::itemChange(change, QVariant(pos()));	
			
		
		
	}

	return QGraphicsRectItem::itemChange(change, value);
}